from datetime import date
from typing import Dict
import pandas as pd
from tqsdk import TqApi, TqAuth,TqAccount,TargetPosTask,TqBacktest
from concurrent.futures import ThreadPoolExecutor
import time
from hybrid_signal import BybridSignal, BybridData

SYMBOL = "SHFE.ag2504"      # 交易合约
STOP_LOSS_POINTS = 30       # 止损点数（根据合约最小变动价位调整）
TRAILING_ENABLED = True     # 是否启用移动止损



#tq = TqApi(web_gui=True,backtest=TqBacktest(start_dt=date(2025, 2, 16), end_dt=date(2025, 2, 19)), auth=TqAuth("xxxx", "xxxx"))

tq = TqApi(account=TqAccount("simnow", "xxxx", "xxxx"),web_gui=True,auth=TqAuth("xxxx", "xxxx"))
pos = TargetPosTask(tq, SYMBOL)

data = BybridData()
data.dk = tq.get_kline_serial(SYMBOL,86400,30)[:-1]
data.hk = tq.get_kline_serial(SYMBOL,3600,60)[:-1]
data.mk = tq.get_kline_serial(SYMBOL,60,120)[:-1]
data.m30k = tq.get_kline_serial(SYMBOL,1800,120)[:-1]
data.m15k = tq.get_kline_serial(SYMBOL,900,120)[:-1]
data.m5k = tq.get_kline_serial(SYMBOL,300,120)[:-1]
quote = tq.get_quote(SYMBOL)

ds = BybridSignal("xxxx","https://api.lkeap.cloud.tencent.com/v1","deepseek-r1")


executor = ThreadPoolExecutor(max_workers=2)
future = None
last_reasoning_time = None 

highest_high = 0    # 持仓期间最高价
lowest_low = 0      # 持仓期间最低价
position = 0        # 当前持仓方向（0：无仓，1：多仓，-1：空仓）

while True:
    try:
        tq.wait_update()
        #print(data.m15k)
    except Exception as e:
        print("runtime error")
    last_price = quote.last_price
    # 多仓处理
    if position == 1:
        # 更新最高价
        if last_price > highest_high:
            highest_high = last_price
            print(f"更新最高价：{highest_high}")
        # 计算回撤
        drawdown = highest_high - last_price
        if drawdown >= STOP_LOSS_POINTS * quote.price_tick:
            pos.set_target_volume(0)  # 平仓
            position = 0
            print(f"多仓止损 平仓价：{last_price} 回撤：{drawdown}点")
            
    # 空仓处理（逻辑对称）
    elif position == -1:
        # 更新最低价
        if last_price < lowest_low:
            lowest_low = last_price
            print(f"更新最低价：{lowest_low}")
            
        # 计算回撤
        drawdown = last_price - lowest_low
        if drawdown >= STOP_LOSS_POINTS * quote.price_tick:
            pos.set_target_volume(0)  # 平仓
            position = 0
            print(f"空仓止损 平仓价：{last_price} 回撤：{drawdown}点")

    if data.m5k.empty or data.m5k.iloc[-1]['datetime'] == last_reasoning_time:
        continue
    if tq._backtest :
        time.sleep(60)
    if future is not None and not future.done() :
        continue
    last_reasoning_time = data.m5k.iloc[-1]['datetime']
    future = executor.submit(ds.reasoning_target_position,data)
    future.add_done_callback(lambda f: pos.set_target_volume(f.result()*100) if f.result() !=0 else None)
    
    print("update")
        
    
    
    
        
